/*
 *  Copyright (C) 2010 Glauco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.dao;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;
import java.util.logging.Level;
import javax.persistence.Column;
import org.balisunrise.annotation.ColumnDefinition;
import org.balisunrise.annotation.ColumnEmbedded;
import org.balisunrise.annotation.ColumnSelection;
import org.balisunrise.annotation.CriteriaDefinition;
import org.balisunrise.annotation.CriteriaEmbedded;
import org.balisunrise.annotation.CriteriaSelection;
import org.balisunrise.annotation.FieldDefinition;
import org.balisunrise.annotation.FieldEmbedded;
import org.balisunrise.annotation.FieldSelection;
import org.balisunrise.annotation.Property;
import org.balisunrise.application.Application;

/**
 * Leitor de Propriedades.
 * @author glacuo
 */
public class PropertiesReader implements org.balisunrise.common.PropertiesReader {

    public PropertiesReader() {
        String language = System.getProperty("user.language");
        if (language.equals("pt")){
            try{
                Properties p = new Properties();
                p.load(PropertiesReader.class.getResourceAsStream(
                        "/org/balisunrise/dao/Properties-PT-BR.properties"));
                Properties sysProps = System.getProperties();
                sysProps.putAll(p);
                System.setProperties(sysProps);
            }catch(IOException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "Não foi possível carregar as propriedades do Aplicativo!", ex);
            }
        }
        else{
            try{
                Properties p = new Properties();
                p.load(PropertiesReader.class.getResourceAsStream(
                        "/org/balisunrise/dao/Properties-EN.properties"));
                Properties sysProps = System.getProperties();
                sysProps.putAll(p);
                System.setProperties(sysProps);
            }catch(IOException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "Can't load application properties!", ex);
            }
        }
    }

    public Properties readFieldProperties(Field field){

        Properties p = new Properties();
        
        if(field.isAnnotationPresent(Column.class)){
            Column c = field.getAnnotation(Column.class);
            p.put("insertable", c.insertable());
            p.put("updatable", c.updatable());
            p.put("nullable", c.nullable());
            p.put("length", c.length());
            p.put("precision", c.precision());
            p.put("scale", c.scale());
        }

        return p;
    }

    /**
     * Propriedades aceitaveis:
     *  - enabled
     *  - mask
     *  - upper
     *  - foreground
     *  - background
     * @param field
     * @return
     */
    public Properties readFieldDefinitionProperties(FieldDefinition field) {

        Properties p = new Properties();

        for (Property prop : field.properties()) {

            String[] values = prop.values();
            if (values.length < 2)
                break;

            p.put(prop.values()[0], decodeProperty(prop));
        }

        return p;
    }

    public Properties readCriteriaDefinitionProperties(CriteriaDefinition criteria) {
        
        Properties p = new Properties();

        for (Property prop : criteria.properties()) {

            String[] values = prop.values();
            if (values.length < 2)
                break;

            p.put(prop.values()[0], decodeProperty(prop));
        }

        return p;
    }

    public Properties readColumnDefinitionProperties(ColumnDefinition column) {

        Properties p = new Properties();

        for (Property prop : column.properties()) {

            String[] values = prop.values();
            if (values.length < 2)
                break;

            p.put(prop.values()[0], decodeProperty(prop));
        }

        return p;
    }

    /**
     * Retorna o valor de uma propriedade.
     * @param name nome da propriedade
     * @return o valor da propriedade, se existir, caso contrario null.
     */
    public String readProperty(String name) {
        return System.getProperty(name);
    }

    /**
     * Verifica se o texto é uma propriedade do sistema.<br>
     * Quando o texto começa com a String <code>PROP</code> (constante da classe
     * <code>PropertiesReader</code>) será buscado o valor da propriedade do
     * sistema.
     *
     * @see #PROP
     * @param text texto.
     * @return o valor da propriedade do sistema ou o próprio texto se não for
     * para ler uma propriedade.
     */
    public String processText(String text) {

        if(text == null)
            return text;

        if (text.startsWith(PROP)){
            String property = text.replaceFirst(PROP, "");
            String result = readProperty(property);
            if (result != null)
                return result;
        }

        return text;
    }

    /**
     * Decodifica uma propriedade.
     *
     * @param prop
     * @return
     */
    private String decodeProperty(Property prop){
        // TODO decodeProperty, verificar para determinadas propriedades.

        return prop.values()[1];
    }

    public Properties readFieldEmbeddedProperties(FieldEmbedded field) {

        Properties p = new Properties();

        for (Property prop : field.properties()) {

            String[] values = prop.values();
            if (values.length < 2)
                break;

            p.put(prop.values()[0], decodeProperty(prop));
        }

        return p;
    }

    public Properties readFieldSelectionProperties(FieldSelection field) {

        Properties p = new Properties();

        for (Property prop : field.properties()) {

            String[] values = prop.values();
            if (values.length < 2)
                break;

            p.put(prop.values()[0], decodeProperty(prop));
        }

        return p;
    }

    public Properties readCriteriaEmbeddedProperties(CriteriaEmbedded criteria) {

        Properties p = new Properties();

        for (Property prop : criteria.properties()) {

            String[] values = prop.values();
            if (values.length < 2)
                break;

            p.put(prop.values()[0], decodeProperty(prop));
        }

        return p;
    }

    public Properties readCriteriaSelectionProperties(CriteriaSelection criteria) {

        Properties p = new Properties();

        for (Property prop : criteria.properties()) {

            String[] values = prop.values();
            if (values.length < 2)
                break;

            p.put(prop.values()[0], decodeProperty(prop));
        }

        return p;
    }

    public Properties readColumnEmbeddedProperties(ColumnEmbedded column) {

        Properties p = new Properties();

        for (Property prop : column.properties()) {

            String[] values = prop.values();
            if (values.length < 2)
                break;

            p.put(prop.values()[0], decodeProperty(prop));
        }

        return p;
    }

    public Properties readColumnSelectionProperties(ColumnSelection column) {

        Properties p = new Properties();

        for (Property prop : column.properties()) {

            String[] values = prop.values();
            if (values.length < 2)
                break;

            p.put(prop.values()[0], decodeProperty(prop));
        }

        return p;
    }
}
